var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');
var { basis, param } = require('./config');

if (fs.existsSync(basis.cocosCreatorPath) == false) {
    return console.log(`cocosCreatorPath路径错误: ${basis.cocosCreatorPath}`);
}

var execCmd = async function (cmd) {
    return new Promise(function (right, error) {
        exec(cmd, function (error, stdout, stderr) {
            right([error, stdout, stderr]);
        });
    })
}

var CreateDirectory = function (dir) {
    if (fs.existsSync(dir) == false) {
        fs.mkdirSync(dir);
    }
}

var DeleteDirectory = function (dir) {
    if (fs.existsSync(dir) == true) {
        var files = fs.readdirSync(dir);
        files.forEach(function (item) {
            var item_path = path.join(dir, item);
            // console.log(item_path);
            if (fs.statSync(item_path).isDirectory()) {
                DeleteDirectory(item_path);
            }
            else {
                fs.unlinkSync(item_path);
            }
        });
        fs.rmdirSync(dir);
    }
}

var CopyDirectory = function (src, dest) {
    if (fs.existsSync(src) == false) {
        return false;
    }

    if (fs.existsSync(dest) == false) {
        fs.mkdirSync(dest);
    }

    // console.log("src:" + src + ", dest:" + dest);
    // 拷贝新的内容进去
    var dirs = fs.readdirSync(src);
    dirs.forEach(function (item) {
        var item_path = path.join(src, item);
        var temp = fs.statSync(item_path);
        if (temp.isFile()) { // 是文件
            // console.log("Item Is File:" + item);
            fs.copyFileSync(item_path, path.join(dest, item));
        } else if (temp.isDirectory()) { // 是目录
            // console.log("Item Is Directory:" + item);
            CopyDirectory(item_path, path.join(dest, item));
        }
    });
}

var TinyDirectory = async function (dir) {
    if (fs.existsSync(dir) == true) {
        var files = fs.readdirSync(dir);
        files.forEach(async function (item) {
            var item_path = path.join(dir, item);
            var item_stat = fs.statSync(item_path);
            if (item_stat.isDirectory()) {
                // 是目录
                TinyDirectory(item_path);
            } else {
                // 是文件
                if (item_stat.size >= basis.tinyImgLimit) {
                    if (item_path.endsWith('.png') || item_path.endsWith('.PNG')) {
                        await execCmd(`${path.join(__dirname, 'pngquant.exe')} -f --ext=.png --speed=1 --quality=20-90 ${item_path}`);
                    } else if (item_path.endsWith('.jpg') || item_path.endsWith('.JPG') || item_path.endsWith('.jpeg') || item_path.endsWith('.JPEG')) {
                        await execCmd(`${path.join(__dirname, 'jpegtran.exe')} -copy none -optimize -progressive ${item_path} ${item_path}`);
                    }
                }
            }
        });
    }
}

var FindFile = function (dir, cb) {
    if (fs.existsSync(dir) == false || !fs.statSync(dir).isDirectory()) {
        return false;
    }

    var files = fs.readdirSync(dir);
    for (let index = 0; index < files.length; index++) {
        var file = files[index];
        var file_path = path.join(dir, file);
        var file_state = fs.statSync(file_path);
        if (file_state.isDirectory()) {
            var result = FindFile(file_path, cb);
            if (result) return result;
        } else {
            const result = cb(file_path, file_state)
            if (result) return result;
        }
    }
}

// 获得构建参数字符串
var getBuildParamStr = function () {
    var str = 'platform=wechatgame';
    for (const key in param) {
        if (key !== 'startScene') {
            str += `;${key}=${param[key]}`;
        } else {
            var startScene = param.startScene ? path.basename(param.startScene, path.extname(param.startScene)) + '.fire.meta' : '.fire.meta';
            var uuid = FindFile('./assets', function (path) {
                if (path.endsWith(startScene)) {
                    console.log(`startScene [${param.startScene}] => ${path}`);
                    return JSON.parse(fs.readFileSync(path, 'utf-8')).uuid;
                }
            })
            if (uuid) {
                str += `;${key}=${uuid}`;
                console.log(`startScene [${param.startScene}] => ${uuid}`);
            } else {
                console.warn(`startScene: [${param.startScene}] 未找到，使用系统默认值`);
            }
        }
    }
    return `${basis.cocosCreatorPath} --path ./ --build "${str}"`;
}

const buildcmd = getBuildParamStr();
const platform = basis.platform;

const main = async function () {
    CreateDirectory('./build-templates');
    CreateDirectory('./build');

    console.log('删除构建');
    DeleteDirectory(`./build/${platform}`);
    DeleteDirectory('./build/wechatgame');
    console.log('删除完成');

    console.log('更新模板');
    DeleteDirectory('./build-templates/wechatgame');
    CopyDirectory(`./cmd/build-templates/${platform}`, './build-templates/wechatgame');
    console.log('更新成功');

    console.log('开始构建');
    let [error, stdout, stderr] = await execCmd(buildcmd);
    if (error || stderr) {
        return console.log('构建失败', error, stdout, stderr);
    }
    CopyDirectory('./build/wechatgame', `./build/${platform}`);
    console.log('构建完成');

    console.log('开始拷贝');
    CopyDirectory(`./cmd/build-copys/${platform}`, `./build/${platform}`);
    console.log('拷贝完成');

    console.log('开始压缩');
    await TinyDirectory(`./build/${platform}`);
    console.log('压缩完成');

    console.log(path.join(__dirname, '../build'));
    await execCmd(`start ${path.join(__dirname, '../build')}`);
}

if (platform === 'wx' || platform === 'tt') {
    main();
} else {
    config.error('platform仅支持wx或tt')
}